<template>
    <el-dialog
        :title="title"
        v-if="conf.dialogVisible"
        top='0px'
        :width='width'
        customClass='el-dialog__no-top-border'
        append-to-body
        destroy-on-close
        :show-close="false"
        :close-on-click-modal="closeOnClickModal"
        @open="handleOpen"
        @opened="handleOpened"
        @close="handleClose"
        @closed="handleClosed"
        v-el-drag-dialog
        :visible.sync="conf.dialogVisible">
        <slot></slot>
        <span slot="footer" class="dialog-footer">
            <el-button size="small" @click="handleCancle">取 消</el-button>
            <el-button type="primary" size="small" v-loading="loading" @click="handleSubmit">确 定</el-button>
        </span>
    </el-dialog>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog'
import Emitter from 'element-ui/src/mixins/emitter'
import Migrating from 'element-ui/src/mixins/migrating'
export default {
  name: 'yc-dialog',
  componentName: 'yc-dialog',
  mixins: [Emitter, Migrating],
  directives: { elDragDialog },
  props: {
    mode: {
      type: String,
      default: 'create'
    },
    width: {
      type: String,
      default: '400px'
    },
    conf: {
      type: Object,
      default: function () {
        return {
          dialogVisible: false
        }
      }
    }
  },
  computed: {
    title () {
      return this.mode === 'create' ? '新建' : '编辑'
    }
  },
  data () {
    return {
      loading: false,
      closeOnClickModal: false
    }
  },
  created () {
  },
  methods: {
    handleOpen () {
      this.$emit('open')
    },
    handleOpened () {
      this.$emit('opened')
    },
    handleClose () {
      this.$emit('close')
    },
    handleClosed () {
      this.$emit('closed')
    },
    handleCancle () {
      this.$emit('on-cancel')
      this.conf.dialogVisible = false
    },
    handleSubmit () {
      var callBackForm = { valid: undefined }
      var callBackTable = { valid: undefined }
      this.broadcast('yc-form', 'validate', callBackForm)
      this.broadcast('yc-table', 'validate', callBackTable)
      if (callBackForm.valid !== undefined && callBackForm.valid === false) {
        return
      }
      if (callBackTable.valid !== undefined && callBackTable.valid === false) {
        return
      }
      this.loading = true
      this.$emit('on-submit', (status) => {
        this.loading = false
        if (status) {
          this.conf.dialogVisible = false
        }
      })
    },
    clearValidate (flag = false) {
      this.broadcast('yc-form', 'restForm', flag || this.mode === 'create')
    }
  }
}
</script>
